import { env, http, parseTime, jsonpToJson, clone } from '../../utils/index.js'
// miniprogram/pages/trend/trend.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    datas: [],
    zhishus: [],
    ver: '',
    show: false,
    today: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    this.setData({
      today: parseTime(null, '{y}-{m}-{d}')
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    this.isHide = false
    if (typeof this.data.isProductionEnv === 'undefined') {
      let isProductionEnv = await env()
      this.setData({
        isProductionEnv
      })
    }
    this.getZhishu()
    await this.getData()

    if (this.interVal) {
      clearInterval(this.interVal)
    }

    this.interVal = setInterval(() => {
      this.getData()
      this.getZhishu()
    }, 60 * 1000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.isHide = true
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: async function () {
    this.getZhishu()
    await this.getData()
    wx.stopPullDownRefresh()

    if (this.interVal) {
      clearInterval(this.interVal)
    }

    this.interVal = setInterval(() => {
      this.getZhishu()
      this.getData({ showLoading: false })
    }, 60 * 1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  showChart (e) {
    let dataset = e.currentTarget.dataset
    wx.previewImage({
      urls: [`http://img1.money.126.net/chart/hs/time/540x360/${dataset.type}${dataset.code}.png?v=${Date.now()}`],
    })
  },
  async getZhishu () {
    if (this.isHide) {
      return
    }
    let zhishus = [
      { code: '000001', name: '上证指数', type: 0 },
      { code: '399001', name: '深证成指', type: 1 },
      { code: '399006', name: '创业板指', type: 1 }
    ]
    let datas = []

    for (let i = 0, len = zhishus.length; i < len; i++) {
      let { type, code } = zhishus[i]
      let todayRes = await http({
        url: `https://img1.money.126.net/data/hs/time/today/${type}${code}.json`,
        method: 'get'
      })
      // 当前值
      let currentValue = todayRes.data.slice(-1)[0][1] || todayRes.yestclose
      // 累积涨跌幅
      let chg = (currentValue - todayRes.yestclose).toFixed(2)
      // 比率
      let chgPercent = ((chg / todayRes.yestclose) * 100).toFixed(2)
      datas.push({ ...zhishus[i], currentValue: Number(currentValue).toFixed(2), chg, chgPercent })
    }

    this.setData({
      zhishus: datas
    })
  },
  async getData () {
    if (this.isHide) {
      return
    }
    if (!this.data.isProductionEnv) {
      // weather
      let datas = [{ "city": "广州", "cityid": "101280101", "temp": "26.6", "WD": "东南风", "WS": "小于3级", "SD": "83%", "AP": "1001.4hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "1.7", "isRadar": "1", "Radar": "JC_RADAR_AZ9200_JB" }, { "city": "惠州", "cityid": "101280301", "temp": "29.3", "WD": "东南风", "WS": "小于3级", "SD": "79%", "AP": "1003.9hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "2", "isRadar": "0", "Radar": "" }, { "city": "梅州", "cityid": "101280401", "temp": "31.3", "WD": "南风", "WS": "小于3级", "SD": "56%", "AP": "995.5hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "2.6", "isRadar": "1", "Radar": "JC_RADAR_AZ9753_JB" }, { "city": "汕头", "cityid": "101280501", "temp": "30", "WD": "西南风", "WS": "小于3级", "SD": "74%", "AP": "1006.4hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "3", "isRadar": "1", "Radar": "JC_RADAR_AZ9754_JB" }, { "city": "深圳", "cityid": "101280601", "temp": "28.3", "WD": "西南风", "WS": "小于3级", "SD": "83%", "AP": "999.3hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "1.3", "isRadar": "1", "Radar": "JC_RADAR_AZ9755_JB" }, { "city": "珠海", "cityid": "101280701", "temp": "28.1", "WD": "西南风", "WS": "小于3级", "SD": "88%", "AP": "1000.7hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "1.7", "isRadar": "0", "Radar": "" }, { "city": "佛山", "cityid": "101280800", "temp": "28.9", "WD": "东南风", "WS": "小于3级", "SD": "80%", "AP": "1003hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "5.3", "isRadar": "0", "Radar": "" }, { "city": "肇庆", "cityid": "101280901", "temp": "30", "WD": "南风", "WS": "小于3级", "SD": "77%", "AP": "1000.2hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "2.5", "isRadar": "0", "Radar": "" }, { "city": "湛江", "cityid": "101281001", "temp": "31.6", "WD": "东南风", "WS": "小于3级", "SD": "75%", "AP": "997.1hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "1.7", "isRadar": "0", "Radar": "" }, { "city": "江门", "cityid": "101281101", "temp": "29.9", "WD": "东南风", "WS": "小于3级", "SD": "80%", "AP": "1002.7hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "2.4", "isRadar": "0", "Radar": "" }, { "city": "河源", "cityid": "101281201", "temp": "27.4", "WD": "南风", "WS": "小于3级", "SD": "84%", "AP": "997.8hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "3.4", "isRadar": "0", "Radar": "" }, { "city": "清远", "cityid": "101281301", "temp": "26.1", "WD": "南风", "WS": "小于3级", "SD": "86%", "AP": "996.3hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "2.6", "isRadar": "0", "Radar": "" }, { "city": "云浮", "cityid": "101281401", "temp": "30.4", "WD": "东北风", "WS": "小于3级", "SD": "66%", "AP": "992.7hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "1", "isRadar": "0", "Radar": "" }, { "city": "潮州", "cityid": "101281501", "temp": "31.9", "WD": "南风", "WS": "小于3级", "SD": "57%", "AP": "1005.7hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "3.2", "isRadar": "0", "Radar": "" }, { "city": "东莞", "cityid": "101281601", "temp": "27.9", "WD": "南风", "WS": "小于3级", "SD": "81%", "AP": "999.9hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "4", "isRadar": "0", "Radar": "" }, { "city": "中山", "cityid": "101281701", "temp": "29.1", "WD": "南风", "WS": "小于3级", "SD": "77%", "AP": "1001.9hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "3.7", "isRadar": "0", "Radar": "" }, { "city": "阳江", "cityid": "101281801", "temp": "27.9", "WD": "南风", "WS": "小于3级", "SD": "92%", "AP": "994.8hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "5.1", "isRadar": "1", "Radar": "JC_RADAR_AZ9662_JB" }, { "city": "揭阳", "cityid": "101281901", "temp": "31.1", "WD": "西南风", "WS": "小于3级", "SD": "55%", "AP": "1001.6hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "2.7", "isRadar": "0", "Radar": "" }, { "city": "茂名", "cityid": "101282001", "temp": "28.7", "WD": "东南风", "WS": "小于3级", "SD": "87%", "AP": "999.8hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "2.7", "isRadar": "0", "Radar": "" }, { "city": "汕尾", "cityid": "101282101", "temp": "29.1", "WD": "南风", "WS": "小于3级", "SD": "77%", "AP": "1005.3hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "4.2", "isRadar": "0", "Radar": "" }, { "city": "韶关", "cityid": "101280201", "temp": "27.4", "WD": "南风", "WS": "小于3级", "SD": "86%", "AP": "990.1hPa", "njd": "暂无实况", "WSE": "<3", "time": "17:50", "sm": "5.4", "isRadar": "1", "Radar": "JC_RADAR_AZ9751_JB" }]
      this.setData({
        show: true,
        datas
      })
      return
    }
    let data
    // 检查缓存是否为今天数据
    let industrys = wx.getStorageSync('industrys')
    if (industrys && (industrys.date == this.data.today)) {
      // 不从后台请求
      data = industrys.data
    } else {
      let { result } = await wx.cloud.callFunction({ name: 'industryTrend' })
      data = result.datas
      wx.setStorage({ key: 'industrys', data: { date: this.data.today, data: data } }) // 只缓存数据库数据
    }

    let dataCopy = clone(data)
    dataCopy.forEach(item => {
      item.loading = true
      item.lastModify = ''
      item.trend_value = ''
    })
    this.setData({
      datas: dataCopy,
      show: true
    })
    this.getIndustryTrendByFE({ industrys: data })
  },
  getDetailData ({ industry }) {
    let { type, code } = industry
    let promises = [
      http({
        url: `https://img1.money.126.net/data/hs/kline/day/times/${type}${code}.json`,
        method: 'get',
        loading: false
      }),
      http({
        url: `https://img1.money.126.net/data/hs/kline/week/times/${type}${code}.json`,
        method: 'get',
        loading: false
      }),
      http({
        url: `https://fundgz.1234567.com.cn/js/${industry.jijin_code}.js`,
        method: 'get',
        loading: false
      }),
      http({
        url: `https://img1.money.126.net/data/hs/time/today/${type}${code}.json`,
        method: 'get',
        loading: false
      }),
      Promise.resolve(industry)
    ]
    return Promise.all(promises)
  },
  async getIndustryTrendByFE ({ industrys }) {
    let promises = []
    industrys.forEach(industry => {
      promises.push(this.getDetailData({ industry }))
    })
    let industrysRes = await Promise.all(promises)

    industrysRes.forEach((industryRes, index) => {
      let [daysRes, weeksRes, guzhi, todayRes, industry] = industryRes
      let { trend_value } = industry
      //  更新ma20day 
      if (daysRes.data) {
        let len = 20
        let closes = daysRes.data.closes.slice(len * -1)
        let ma = sum(closes) / len
        industry.ma20day = ma.toFixed(2)
        industry.ma20day_fix = (industry.ma20day / (1 + 0.01)).toFixed(2)
      }
      // 更新ma5week
      if (weeksRes.data) {
        let len = 5
        let closes = weeksRes.data.closes.slice(len * -1)
        let ma = sum(closes) / len
        industry.ma5week = ma.toFixed(2)
        industry.ma5week_fix = (industry.ma5week / (1 + 0.01)).toFixed(2)
      }

      let needUpdateTrend = false
      guzhi = jsonpToJson(guzhi)
      industry.guzhi = guzhi.gszzl
      let currentValue = todayRes.data.slice(-1)[0][1]
      industry.totalChg = (((currentValue - industry.lastPrice) / industry.lastPrice) * 100).toFixed(2)

      if (trend_value && ((currentValue < industry.ma20day_fix) && (currentValue < industry.ma5week_fix))) {
        industry.trend_value = 0
        needUpdateTrend = true
      }
      // 下降时 若满足条件则更新为下降
      if (!trend_value && ((currentValue >= industry.ma20day * 1.01) && (currentValue >= industry.ma5week * 1.01))) {
        industry.trend_value = 1
        needUpdateTrend = true
      }

      if (needUpdateTrend) {
        industry.lastPrice = currentValue
        industry.lastModify = parseTime(null, '{y}-{m}-{d}')
      }

      industry.loading = false
      this.setData({
        [`datas[${index}]`]: industry
      })
    })

    return false
  },
  async getIndustryTrendByFE2 ({ industrys }) {

    let data = []
    for (let industry of industrys) {
      let { type, code, trend_value } = industry

      // 更新ma20day ma5week
      let daysRes = await http({
        url: `https://img1.money.126.net/data/hs/kline/day/times/${type}${code}.json`,
        method: 'get',
        loading: false
      })
      if (daysRes.data) {
        let len = 20
        let closes = daysRes.data.closes.slice(len * -1)
        let ma = sum(closes) / len
        industry.ma20day = ma.toFixed(2)
        industry.ma20day_fix = (industry.ma20day / (1 + 0.01)).toFixed(2)
      }
      let weeksRes = await http({
        url: `https://img1.money.126.net/data/hs/kline/week/times/${type}${code}.json`,
        method: 'get',
        loading: false
      })

      if (weeksRes.data) {
        let len = 5
        let closes = weeksRes.data.closes.slice(len * -1)
        let ma = sum(closes) / len
        industry.ma5week = ma.toFixed(2)
        industry.ma5week_fix = (industry.ma5week / (1 + 0.01)).toFixed(2)
      }
      // 请求当前估值
      let needUpdateTrend = false
      let guzhi = await http({
        url: `https://fundgz.1234567.com.cn/js/${industry.jijin_code}.js`,
        method: 'get',
        loading: false
      })

      guzhi = jsonpToJson(guzhi)
      industry.guzhi = guzhi.gszzl
      let todayRes = await http({
        url: `https://img1.money.126.net/data/hs/time/today/${type}${code}.json`,
        method: 'get',
        loading: false
      })
      let currentValue = todayRes.data.slice(-1)[0][1]
      industry.totalChg = (((currentValue - industry.lastPrice) / industry.lastPrice) * 100).toFixed(2)

      if (trend_value && ((currentValue < industry.ma20day_fix) && (currentValue < industry.ma5week_fix))) {
        industry.trend_value = 0
        needUpdateTrend = true
      }
      // 下降时 若满足条件则更新为下降
      if (!trend_value && ((currentValue >= industry.ma20day * 1.01) && (currentValue >= industry.ma5week * 1.01))) {
        industry.trend_value = 1
        needUpdateTrend = true
      }

      if (needUpdateTrend) {
        industry.lastPrice = currentValue
        industry.lastModify = parseTime(null, '{y}-{m}-{d}')
      }
      data.push(industry)
      this.setData({
        datas: data,
        show: true
      })
    }
    return data
  },

})